package cn.gx.dao.impl;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SessionFactory;

import cn.gx.dao.BaseDao;

/**
 * dao 基类实现
 * @author always
 *
 * @param <T>
 */
@SuppressWarnings("unchecked")
public abstract class BaseDaoImpl<T> implements BaseDao<T>{

	
	@Resource(name="sessionFactory")
	private SessionFactory sf;
	private Class<T> clazz;

	public BaseDaoImpl(){
		ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
		clazz = (Class<T>) type.getActualTypeArguments()[0];
		System.out.println("clazz:"+clazz+",实际type:"+type.getActualTypeArguments()+",泛型："+type);
	}
	
	public void saveEntity(T t) {
		// TODO Auto-generated method stub
		sf.getCurrentSession().save(t);
	}

	public void updateEntity(T t) {
		// TODO Auto-generated method stub
		sf.getCurrentSession().update(t);
	}

	public void saveOrUpdateEntity(T t) {
		// TODO Auto-generated method stub
		sf.getCurrentSession().saveOrUpdate(t);
	}

	public void deleteEntity(T t) {
		// TODO Auto-generated method stub
		sf.getCurrentSession().delete(t);
	}

	public void batchEntityByHQL(String hql, Object... objects) {
		
		Query query = sf.getCurrentSession().createQuery(hql);
		int len=objects.length;
		for(int i=0;i<len;i++){
			query.setParameter(i, objects[i]);
		}
		query.executeUpdate();
	}

	public void batchEntityBySQL(String sql,Object...objects){
		
		Query query=sf.getCurrentSession().createSQLQuery(sql);
		int len=objects.length;
		for(int i=0;i<len;i++){
			query.setParameter(i, objects[i]);
		}
		query.executeUpdate();
	}
	
	public T getEntity(Integer id) {
		// TODO Auto-generated method stub
		//在超类中得到每个子类所制定的泛型
		return (T) sf.getCurrentSession().get(clazz, id);
	}

	public T loadEntity(Integer id) {
		// TODO Auto-generated method stub
		return (T) sf.getCurrentSession().load(clazz, id);
	}

	public List<T> findEntityByHQL(String hql, Object... objects) {
		Query query = sf.getCurrentSession().createQuery(hql);
		int len=objects.length;
		for(int i=0;i<len;i++){
			query.setParameter(i, objects[i]);
		}
		return query.list();
	}

	
}
